﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using System.Collections.Generic;
using PowerStation.RequestModel;
using Microsoft.EntityFrameworkCore;
using adb.excel;
using System.IO;
using Masuit.Tools;
using Microsoft.Net.Http.Headers;
using System;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 电站管理
    /// </summary>
    public class PowerStationController : BaseApi<PowerStationController>
    {
        /// <summary>
        /// 电站管理
        /// </summary>
        /// <param name="content"></param>
        public PowerStationController(IHttpContextAccessor content) : base(content)
        {
        }

        #region 电站管理
        /// <summary>
        /// 创建电站
        /// </summary>
        /// <returns>返回创建后的ID</returns>
        [HttpPost]
        public async Task<ResultApi<long>> Create(RequestAddPowerStation req)
        {
            var model = (tPowerStation)req;
            //省ID添加
            var shengNum = await this._db.tKey.FirstOrDefaultAsync(x=>x.keyName == req.powerStationSheng_keyName && x.keyType == 6);
            model.powerStationShengId = (int?)shengNum.keyId;
            //市县ID添加
            var cityNum = await this._db.tKey.FirstOrDefaultAsync(x=>x.keyName == req.powerStationShi_keyName && x.keyType == 6);
            model.powerStationCity_keyId_fk = cityNum.keyId;
            if (req.powerStationXian_keyName != null)
            {   
                var xianNum = await this._db.tKey.FirstOrDefaultAsync(x=>x.keyName == req.powerStationXian_keyName && x.keyType == 6);
                model.powerStationXianId = (int?)xianNum.keyId;
            }

            model.powerStationId = 0;
            model.dataState = 0;
            model.addTime = System.DateTime.Now;
            if (string.IsNullOrEmpty(model.powerStationNo) || await this._db.tPowerStation.AnyAsync(x => x.powerStationNo == model.powerStationNo))
            {
                return ResultApi.error<long>(0, "不能填写空或重复的电站编号");
            }
            await this._db.tPowerStation.AddAsync(model);
            await this._db.SaveChangesAsync();

            //选择初始化硬件的电站Id
            if (req.initPowerStationId.HasValue && model.powerStationId > 0)
            {
                var initPowerStation = this._db.tPowerStation.FirstOrDefault(x => x.powerStationId == req.initPowerStationId);
                var initdeviceModel = this._db.tDevice.FirstOrDefault(x => x.station_device_powerStationId_fk == req.initPowerStationId);

                if (initPowerStation != null)
                {
                    //获取初始化电站的硬件清单(排除监控,需要另外添加)
                    var initDeviceList = await this._db.tPowerStationDevice.Where(x => x.devicePowerStation_powerStationId_fk == req.initPowerStationId && x.deviceType_keyId_fk != 820004).ToListAsync();
                    initDeviceList.ForEach(item =>
                    {
                        item.deviceId = 0;
                        item.addTime = DateTime.Now;
                        item.devicePowerStation_powerStationId_fk = model.powerStationId;
                        item.deviceTopic = item.deviceTopic.Replace($"/{initPowerStation.powerStationNo}", $"/{model.powerStationNo}");
                    });
                    await this._db.tPowerStationDevice.AddRangeAsync(initDeviceList);
                    await this._db.tDevice.AddAsync(new tDevice
                    {
                        station_device_powerStationId_fk = model.powerStationId,
                        account = model.powerStationNo,
                        password = model.powerStationNo,
                        deviceSN = initdeviceModel.deviceSN,
                    });
                    //向tStatisticsSingleData添加数据，才可以更新视图
                    //tStatisticsSingleData singleData = new tStatisticsSingleData();
                    /*decimal planinstall = 0;
                    if (req.powerStationDuals.Select(x=>x.deviceGroup).ToString() != "" && req.powerStationDuals.Select(x => x.deviceGroup).ToString() != null)
                    {
                        foreach (var item in req.powerStationDuals)
                        {
                            planinstall = planinstall + item.installed;
                            await this._deviceDB.tStatisticsSingleData.AddAsync(new tStatisticsSingleData
                            {
                                powerStation_SingleData_powerStationId_fk = model.powerStationId,
                                deviceGroup = item.deviceGroup,
                                installed = item.installed,
                                installedCapacity = item.installed,
                                planInstalled = 0,
                                addTime = DateTime.Now
                            });
                        }
                        await this._deviceDB.tStatisticsSingleData.Where(x => x.powerStation_SingleData_powerStationId_fk == model.powerStationId).UpdateAsync(data => data.planInstalled == planinstall);
                    }*/
                    await this._db.SaveChangesAsync();
                    //await this._deviceDB.SaveChangesAsync();
                }
            }
            return ResultApi.okOrError(true, model.powerStationId);
        }


        /// <summary>
        /// 修改电站
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> Modify(RequestAddPowerStation model)
        {
            if (string.IsNullOrEmpty(model.powerStationNo) || await this._db.tPowerStation.AnyAsync(x => x.powerStationId != model.powerStationId && x.powerStationNo == model.powerStationNo))
            {
                return ResultApi.error(false, "不能填写空或重复的电站编号");
            }
            //省ID添加
            long shengNum = 0;
            long cityNum = 0;
            int xianNum = 0;
            if (model.powerStationSheng_keyName != null && !model.powerStationSheng_keyName.Equals(""))
            {
                var sheng = await this._db.tKey.FirstOrDefaultAsync(x => x.keyName == model.powerStationSheng_keyName && x.keyType == 6);
                shengNum = sheng.keyId;
            }
            //市县ID添加
            if (model.powerStationShi_keyName != null && !model.powerStationShi_keyName.Equals(""))
            {
                var city = await this._db.tKey.FirstOrDefaultAsync(x => x.keyName == model.powerStationShi_keyName && x.keyType == 6);
                cityNum = city.keyId;
            }
            if (model.powerStationXian_keyName != null && !model.powerStationXian_keyName.Equals(""))
            {
                var xian = await this._db.tKey.FirstOrDefaultAsync(x => x.keyName == model.powerStationXian_keyName && x.keyType == 6);
                xianNum = (int)xian.keyId;
            }
            await this._db.tPowerStation.Where(x => x.powerStationId == model.powerStationId).UpdateAsync(x => new tPowerStation()
            {
                companyDes = model.companyDes,
                powerStationName = model.powerStationName,
                powerStationNo = model.powerStationNo,
                securityDay = model.securityDay,
                sort = model.sort,
                companyName = model.companyName,
                powerStationArea_keyId_fk = model.powerStationArea_keyId_fk,
                powerStationCity_keyId_fk = cityNum,
                powerStationShengId = (int?)shengNum,
                powerStationXianId = xianNum,
                powerStationDrainageArea_keyId_fk = model.powerStationDrainageArea_keyId_fk,
                powerStationType_keyId_fk = model.powerStationType_keyId_fk,
                upPrice = model.upPrice,

            });
            decimal planData = model.powerStationDuals.AsQueryable().Sum(x=>x.installed);
            
            foreach (var item in model.powerStationDuals)
            {
                var CharpToUpadate = this._deviceDB.tStatisticsSingleData.Where(x => x.powerStation_SingleData_powerStationId_fk == model.powerStationId && x.deviceGroup != "public" && x.deviceGroup == item.deviceGroup);
                if (CharpToUpadate.Count() == 0)
                {
                    tStatisticsSingleData singleData = new tStatisticsSingleData()
                    {
                        powerStation_SingleData_powerStationId_fk = model.powerStationId,
                        deviceGroup = item.deviceGroup,
                        installed = item.installed,
                        installedCapacity = item.installed,
                        addTime = DateTime.Now,
                        planInstalled = planData,
                        deviceType = item.deviceType
                    };
                    await this._deviceDB.tStatisticsSingleData.AddAsync(singleData);
                }
                else
                {
                    await CharpToUpadate.UpdateAsync(x => new tStatisticsSingleData
                    {
                        powerStation_SingleData_powerStationId_fk = model.powerStationId,
                        deviceGroup = item.deviceGroup,
                        installed = item.installed,
                        installedCapacity = item.installed,
                        addTime = DateTime.Now,
                        planInstalled = planData,
                        deviceType = item.deviceType
                    });
                }
            }
            await this._deviceDB.SaveChangesAsync();
            return ResultApi.okOrError<bool>(true, true);
        }

        /// <summary>
        /// 获取电站列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<StatisticsSinglevPowerStation>>> List([FromQuery] RequestMultipleSearchModel model)
        {
            IQueryable<vPowerStation> q = this._db.vPowerStation;
            var statistics = this._deviceDB.vStatisticsSingleData.Where(x => !x.deviceGroup.Contains("public"))
                                                                 .GroupBy(data => data.powerStationId)
                                                                 .Select(group => new PowerStationDual
                                                                 {
                                                                     powerStationId = group.Key,
                                                                     installed = group.Sum(data => data.installed)
                                                                 });
            IQueryable<StatisticsSinglevPowerStation> ssp = await StationDataReplace(q, statistics);
            //q = q.ToList().ConvertAll<StatisticsSinglevPowerStation>()
            foreach (var item in model.searchItem)
            {
                if (item.typeName == "电站名称")
                {
                    ssp = ssp.Where(x => x.powerStationName.Contains(item.value));
                }
                else if (item.typeName == "电站类型")
                {
                    ssp = ssp.Where(x => x.powerStationType_keyId_fk == item.value.ConvertTo<long>());
                }
                else if (item.typeName == "所属片区")
                {
                    ssp = ssp.Where(x => x.powerStationArea_keyId_fk == item.value.ConvertTo<long>());
                }
            }
            var result = await model.setPageAsync(ssp.ToList());
            var lst = result.Item2.ToList();

            return ResultApi.ok<List<StatisticsSinglevPowerStation>>(lst, result.Item1);
        }

        private Task<IQueryable<StatisticsSinglevPowerStation>> StationDataReplace(IQueryable<vPowerStation> q, IQueryable<PowerStationDual> statistics)
        {
            var qlist = q.ToListDynamic();
            var slist = statistics.ToListDynamic();
            List<StatisticsSinglevPowerStation> statisticsSinglevPowerStations = new List<StatisticsSinglevPowerStation>();

            foreach (var item in qlist)
            {
                decimal id = 0;
                foreach (var sid in slist)
                {
                    if (item.powerStationId == sid.powerStationId)
                    {
                        id = sid.installed;
                        continue;
                    }
                }
                StatisticsSinglevPowerStation statisticsSinglevPowerStation = new StatisticsSinglevPowerStation
                {
                    addTime = item.addTime,
                    cityName = item.cityName,
                    companyDes = item.companyDes,
                    companyName = item.companyName,
                    dataState = item.dataState,
                    drainageName = item.drainageName,
                    installed = id,
                    keyName = item.keyName,
                    MessageNotReadCount = item.MessageNotReadCount,
                    powerStationSheng_keyName = item.ShengName,
                    powerStationShi_keyName = item.cityName,
                    powerStationXian_keyName = item.XianName,
                    powerStationArea_keyId_fk = item.powerStationArea_keyId_fk,
                    powerStationCity_keyId_fk = item.powerStationCity_keyId_fk,
                    powerStationDrainageArea_keyId_fk = item.powerStationDrainageArea_keyId_fk,
                    powerStationId = item.powerStationId,
                    powerStationName = item.powerStationName,
                    powerStationNo = item.powerStationNo,
                    powerStationTypeName = item.powerStationTypeName,
                    powerStationType_keyId_fk = item.powerStationType_keyId_fk,
                    progress_keyId_fk = item.progress_keyId_fk,
                    securityDay = item.securityDay,
                    sort = item.sort,
                    upPrice = item.upPrice
                };
                statisticsSinglevPowerStations.Add(statisticsSinglevPowerStation);
            }

            return Task.FromResult(statisticsSinglevPowerStations.AsQueryable());
        }

        /// <summary>
        /// 导出电站数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FileStreamResult> Download([FromQuery] RequestMultipleSearchModel model)
        {
            var m = await this.List(model);
            var titles = await this._db.tExcelTitle.Where(x => x.excelType == 3).ToListAsync();
            if (titles.Count == 0) return new FileStreamResult(new MemoryStream(), new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            Task<Stream> task = Task.Run(async () =>
            {
                return ExcelExport.export(m.data, titles);
            });
            return new FileStreamResult(await task, new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }

        /// <summary>
        /// 获取电站机组数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<string>>> GroupGet(decimal powerStationId)
        {
            var powerstation = await this._db.tPowerStationDevice.Where(x => x.devicePowerStation_powerStationId_fk == powerStationId
            && x.deviceTopic.Contains("analog")
            && !x.deviceTopic.Contains("public"))
                .Select(dual => dual.deviceGroup)
                .ToListAsync();
            if (powerstation.Count == 0)
            {
                return ResultApi.ok<List<string>>(null);
            }
            return ResultApi.ok<List<string>>(powerstation);
        }

        /// <summary>
        /// 获取电站详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<StatisticsSinglevPowerStation>> Detail(decimal powerStationId)
        {
            var powerstation = await this._db.vPowerStation.FirstOrDefaultAsync(x => x.powerStationId == powerStationId);
            StatisticsSinglevPowerStation ssp = await StationDataReplace(powerstation);
            return ResultApi.ok<StatisticsSinglevPowerStation>(ssp, 0);
        }

        private async Task<StatisticsSinglevPowerStation> StationDataReplace(vPowerStation powerstation)
        {
            var wherelist = this._deviceDB.tStatisticsSingleData.Where(x => x.powerStation_SingleData_powerStationId_fk == powerstation.powerStationId && !x.deviceGroup.Contains("public"));
            if (wherelist.Count() == 0)
            {
                var grouplist = await this._deviceDB.tStatisticsSingleData.Where(x => x.powerStation_SingleData_powerStationId_fk == powerstation.powerStationId)
                    .Select(data=> new PowerStationDual {
                                    powerStationId = data.powerStation_SingleData_powerStationId_fk,
                                    deviceGroup = data.deviceGroup,
                                    installed = 0,
                                    deviceType = data.deviceType
                    }).ToListAsync();
                StatisticsSinglevPowerStation statisticsSingle = new StatisticsSinglevPowerStation
                {
                    addTime = powerstation.addTime,
                    cityName = powerstation.cityName,
                    companyDes = powerstation.companyDes,
                    companyName = powerstation.companyName,
                    dataState = powerstation.dataState,
                    drainageName = powerstation.drainageName,
                    installed = 0,
                    powerStationDuals = grouplist,
                    keyName = powerstation.keyName,
                    MessageNotReadCount = powerstation.MessageNotReadCount,
                    powerStationArea_keyId_fk = powerstation.powerStationArea_keyId_fk,
                    powerStationCity_keyId_fk = powerstation.powerStationCity_keyId_fk,
                    powerStationDrainageArea_keyId_fk = powerstation.powerStationDrainageArea_keyId_fk,
                    powerStationId = powerstation.powerStationId,
                    powerStationName = powerstation.powerStationName,
                    powerStationNo = powerstation.powerStationNo,
                    powerStationTypeName = powerstation.powerStationTypeName,
                    powerStationType_keyId_fk = powerstation.powerStationType_keyId_fk,
                    progress_keyId_fk = powerstation.progress_keyId_fk,
                    securityDay = powerstation.securityDay,
                    sort = powerstation.sort,
                    upPrice = powerstation.upPrice,
                    powerStationSheng_keyName = powerstation.ShengName,
                    powerStationShi_keyName = powerstation.cityName,
                    powerStationXian_keyName = powerstation.XianName
                };
                return statisticsSingle;
            }
            else
            {
                var installedNew = wherelist.Select(group => new PowerStationDual
                {
                    powerStationId = group.powerStation_SingleData_powerStationId_fk,
                    deviceGroup = group.deviceGroup,
                    installed = group.installed,
                    deviceType = group.deviceType
                }).ToList();
                decimal incount = installedNew.AsQueryable().Where(x=>x.powerStationId == powerstation.powerStationId).Sum(group=>group.installed);
                
                StatisticsSinglevPowerStation statisticsSinglevPowerStation = new StatisticsSinglevPowerStation
                {
                    addTime = powerstation.addTime,
                    cityName = powerstation.cityName,
                    companyDes = powerstation.companyDes,
                    companyName = powerstation.companyName,
                    dataState = powerstation.dataState,
                    drainageName = powerstation.drainageName,
                    installed = incount,
                    powerStationDuals = installedNew,
                    keyName = powerstation.keyName,
                    MessageNotReadCount = powerstation.MessageNotReadCount,
                    powerStationArea_keyId_fk = powerstation.powerStationArea_keyId_fk,
                    powerStationCity_keyId_fk = powerstation.powerStationCity_keyId_fk,
                    powerStationDrainageArea_keyId_fk = powerstation.powerStationDrainageArea_keyId_fk,
                    powerStationId = powerstation.powerStationId,
                    powerStationName = powerstation.powerStationName,
                    powerStationNo = powerstation.powerStationNo,
                    powerStationTypeName = powerstation.powerStationTypeName,
                    powerStationType_keyId_fk = powerstation.powerStationType_keyId_fk,
                    progress_keyId_fk = powerstation.progress_keyId_fk,
                    securityDay = powerstation.securityDay,
                    sort = powerstation.sort,
                    upPrice = powerstation.upPrice,
                    powerStationSheng_keyName = powerstation.ShengName,
                    powerStationShi_keyName = powerstation.cityName,
                    powerStationXian_keyName = powerstation.XianName
                };
                return statisticsSinglevPowerStation;

            }
        }


        /// <summary>
        /// 删除电站信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> Delete(List<decimal> powerStationIds)
        {
            int count = await this._db.tPowerStation.Where(x => powerStationIds.Contains(x.powerStationId)).UpdateAsync(x => new tPowerStation()
            {
                dataState = 1,
            });
            if (count == powerStationIds.Count()) await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count == powerStationIds.Count(), count == powerStationIds.Count());
        }


        #endregion
        #region 峰谷平
        /// <summary>
        /// 判断时是否有交集,只判断时间,返回真就是有时间交集
        /// </summary>
        /// <param name="list">时间列表</param>
        /// <returns></returns>
        private bool checkDateTime(List<tGenerateElctricityTypeTime> list)
        {
            List<Tuple<int, DateTime>> orderList = new List<Tuple<int, DateTime>>();
            int i = 0;
            foreach (var item in list)
            {
                orderList.Add(new Tuple<int, DateTime>(i, item.timeStart));
                orderList.Add(new Tuple<int, DateTime>(i++, item.timeEnd));
            }
            orderList = orderList.OrderBy(x => x.Item2).ToList();
            var beforeInt = -1;
            var afterInt = 0;
            foreach (var item in orderList)
            {
                if (beforeInt != -1 && item.Item1 != beforeInt)
                    return true;
                if (afterInt++ % 2 == 0)
                    beforeInt = item.Item1;
                else
                    beforeInt = -1;
            }
            return false;
        }
        /// <summary>
        /// 保存电站峰谷平数据
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> GenerateElctricityTypeModify(RequestGenerateElctricityTypeModel model)
        {
            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                model.model.dateStart = model.model.dateStart.Date;
                model.model.dateEnd = model.model.dateEnd.Date;
                if (model.model.dateStart <= DateTime.Now.Date)
                {
                    return ResultApi.error(false, "开始参与统计的生效时间要大于今天.请重新选择生效时间");
                }
                if (model.model.dateStart > model.model.dateEnd)
                {
                    return ResultApi.error(false, "生效时间异常,开始时间大于结束时间");
                }
                if (checkDateTime(model.lst))
                {
                    return ResultApi.error(false, "选择的时间有交叉");
                }

                if (model.model.dateStart >= model.model.dateEnd) return ResultApi.error(false, "生效时间错误");
                //判断没有没重叠的日期段

                var lst = await this._db.tGenerateElectricityType.Where(x => x.powerStation_powerStationId_fk == model.model.powerStation_powerStationId_fk && !(model.model.dateStart > x.dateEnd || model.model.dateEnd < x.dateStart)).ToListAsync();//重叠时间段
                if (lst.Any() && model.model.generateElectricityTypeId > 0 && lst.Any(x => x.geType == model.model.geType && model.model.generateElectricityTypeId != x.generateElectricityTypeId))
                {
                    return ResultApi.error(false, "日期段有重叠");
                }
                else if (lst.Any() && model.model.generateElectricityTypeId == 0 && lst.Any(x => x.geType == model.model.geType))
                {
                    return ResultApi.error(false, "日期段有重叠");
                }
                if (lst.Any())
                {
                    var otherLst = lst.Where(x => x.generateElectricityTypeId != model.model.generateElectricityTypeId).Select(c => c.generateElectricityTypeId).ToList();
                    if (otherLst.Any())
                    {
                        var timeLst = await this._db.tGenerateElctricityTypeTime.Where(x => otherLst.Contains((long)x.type_generateElectricityTypeId_fk)).ToListAsync();
                        if (timeLst.Any())
                        {
                            var dd = model.lst.First().timeStart.Date;
                            List<tGenerateElctricityTypeTime> checkTimeList = timeLst.Select(x =>
                            {
                                x.timeStart = new DateTime(dd.Year, dd.Month, dd.Day, x.timeStart.Hour, x.timeStart.Minute, x.timeStart.Second);
                                x.timeEnd = new DateTime(dd.Year, dd.Month, dd.Day, x.timeEnd.Hour, x.timeEnd.Minute, x.timeEnd.Second);
                                return x;
                            }).ToList();

                            //判断有没有重叠的时间段
                            foreach (var item in model.lst)
                            {
                                timeLst.Add(item);
                            }
                            if (checkDateTime(timeLst))
                                return ResultApi.error(false, "选择的时间有交叉");
                        }
                    }
                }
                if (model.model.generateElectricityTypeId > 0)
                {
                    int count = await this._db.tGenerateElectricityType.Where(x => x.generateElectricityTypeId == model.model.generateElectricityTypeId).UpdateAsync(x => new tGenerateElectricityType()
                    {
                        dateEnd = model.model.dateEnd,
                        powerStation_powerStationId_fk = model.model.powerStation_powerStationId_fk,
                        dateStart = model.model.dateStart,
                        geType = model.model.geType,
                    });
                    await this._db.SaveChangesAsync();
                    if (count != 1) return ResultApi.error(false, "修改日期范围出错");
                }
                else
                {
                    await this._db.tGenerateElectricityType.AddAsync(model.model);
                    await this._db.SaveChangesAsync();
                }
                await this._db.tGenerateElctricityTypeTime.Where(x => x.type_generateElectricityTypeId_fk == model.model.generateElectricityTypeId).DeleteAsync();
                await this._db.SaveChangesAsync();
                await this._db.tGenerateElctricityTypeTime.AddRangeAsync(model.lst.Select(x => new tGenerateElctricityTypeTime()
                {
                    timeEnd = new DateTime(model.model.dateStart.Year, model.model.dateStart.Month, model.model.dateStart.Day, x.timeEnd.Hour, x.timeEnd.Minute, 0),
                    timeStart = new DateTime(model.model.dateStart.Year, model.model.dateStart.Month, model.model.dateStart.Day, x.timeStart.Hour, x.timeStart.Minute, 0),
                    gettID = 0,
                    type_generateElectricityTypeId_fk = model.model.generateElectricityTypeId
                }));
                await this._db.SaveChangesAsync();
                await tran.CommitAsync();
            }
            return ResultApi.okOrError<bool>(true, true);
        }


        /// <summary>
        /// 电站峰谷平数据列表,查询中searchItem要函数"电站ID"
        /// </summary>
        /// <param name="model">分页</param>
        /// <param name="powerStationId">电站ID</param>
        /// <param name="type">峰谷平类型,1表示峰期,2表示平期3,表示谷期</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestGenerateElctricityTypeModel>>> GenerateElctricityTypeList([FromQuery] PageModel model, decimal powerStationId, int? type)
        {
            IQueryable<tGenerateElectricityType> q = this._db.tGenerateElectricityType;
            q = q.Where(x => x.powerStation_powerStationId_fk == powerStationId);
            if (type.HasValue)
            {
                q = q.Where(x => x.geType == type);
            }
            var q1 = q.Select(x => new RequestGenerateElctricityTypeModel()
            {
                model = x,
                lst = this._db.tGenerateElctricityTypeTime.Where(k => k.type_generateElectricityTypeId_fk == x.generateElectricityTypeId).ToList(),
            });
            var result = await model.setPageAsync(q1);
            return ResultApi.ok<List<RequestGenerateElctricityTypeModel>>(await result.Item2.ToListAsync(), result.Item1); ;
        }


        /// <summary>
        /// 删除峰谷平数据
        /// </summary>
        /// <param name="generateElectricityTypeIds"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> GenerateElctricityTypeDelete(List<long> generateElectricityTypeIds)
        {
            var m = await this._db.tGenerateElectricityType.Where(x => generateElectricityTypeIds.Contains(x.generateElectricityTypeId)).ToListAsync();
            if (m == null || m.Any() == false) return ResultApi.error(false, "数据丢失");
            foreach (var item in m)
            {
                await this.IsCheckPowerStation(item.powerStation_powerStationId_fk);
            }

            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tGenerateElectricityType.Where(x => generateElectricityTypeIds.Contains(x.generateElectricityTypeId)).DeleteAsync();
                await this._db.tGenerateElctricityTypeTime.Where(x => generateElectricityTypeIds.Contains(x.type_generateElectricityTypeId_fk)).DeleteAsync();
                await this._db.SaveChangesAsync();
                await tran.CommitAsync();
            }
            return ResultApi.okOrError<bool>(true, true);
        }

        #endregion
        #region 电站电器图表

        /// <summary>
        /// 电站电器图片新增接口,同一个电站,名称是唯一值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<decimal>> DiagramCreate(tPowerStateDiagram model)
        {
            await IsCheckPowerStation(model.disgramPowerState_powerStationId_fk);
            model.powerStateDiagramId = 0;
            var m = await this._db.tPowerStateDiagram.FirstOrDefaultAsync(x => x.powerStateDiagramName == model.powerStateDiagramName && x.disgramPowerState_powerStationId_fk == model.disgramPowerState_powerStationId_fk);
            if (m != null) return ResultApi.error<decimal>(0, "电站图表名称是唯一,请不要新建重复名称");
            await this._db.tPowerStateDiagram.AddAsync(model);
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<decimal>(model.powerStateDiagramId > 0, model.powerStateDiagramId);
        }


        /// <summary>
        /// 电站电器图片修改接口
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> DiagramModify(tPowerStateDiagram model)
        {
            await IsCheckPowerStation(model.disgramPowerState_powerStationId_fk);
            var len = await this._db.tPowerStateDiagram.Where(x => x.powerStateDiagramId == model.powerStateDiagramId).UpdateAsync(x => new tPowerStateDiagram { diagramFileId_fileId_fk = model.diagramFileId_fileId_fk, powerStateDiagramDes = model.powerStateDiagramDes });
            return ResultApi.okOrError<bool>(len == 1, len == 1);
        }


        /// <summary>
        /// 电站电器图表删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> DiagramDelete(int powerStateDiagramId)
        {
            var m = await this._db.tPowerStateDiagram.FirstOrDefaultAsync(x => x.powerStateDiagramId == powerStateDiagramId);
            if (m == null) return ResultApi.error(false, "删除失败,数据不存在");
            await IsCheckPowerStation(m.disgramPowerState_powerStationId_fk);
            var ok = await this._db.tPowerStateDiagram.Where(x => x.powerStateDiagramId == powerStateDiagramId).DeleteAsync();
            return ResultApi.okOrError<bool>(ok == 1, ok == 1);
        }


        /// <summary>
        /// 电站电器图表列表
        /// </summary>
        /// <returns></returns>
        /// <param name="powerStationId">电站列表</param>
        /// <param name="searchName">搜索名称,全等搜索</param>
        [HttpGet]
        public async Task<ResultApi<List<tPowerStateDiagram>>> DiagramList(int powerStationId, string searchName = "")
        {
            IQueryable<tPowerStateDiagram> q = this._db.tPowerStateDiagram;
            q = q.Where(q => q.disgramPowerState_powerStationId_fk == powerStationId);
            if (string.IsNullOrWhiteSpace(searchName) == false)
            {
                q = q.Where(x => x.powerStateDiagramName == searchName);
            }
            return ResultApi.ok<List<tPowerStateDiagram>>(await q.ToListAsync(), 0);
        }
        #endregion
    }
}
